package com.wdc.binarytree;

import java.util.Arrays;

@SuppressWarnings("all")
public class Eo2LeetCode105 {



    public static void main(String[] args) {
        TreeNode treeNode = buildTree(new int[]{3, 9, 20, 15, 7}, new int[]{9, 3, 15, 20, 7});
        System.out.println(treeNode);

    }
    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0){
            return null;
        }
        //根据先序遍历确定根节点在中序中的索引，右边是根节点的右子树，左边是根节点的左子树
        //找到根节点后把其加入TreeNode 中
        int rootNum = 0;
        TreeNode root = new TreeNode(preorder[0]);
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == root.val){
                //找到了，左边的就是左子树部分，右边的是右子树部分,记录当前的索引
                int[] inleft = Arrays.copyOfRange(inorder,0,i);  //[9 ]
                int[] inRight = Arrays.copyOfRange(inorder,i + 1,inorder.length); //[2 3 4]

                //找到前序的左右子数，后面用于递归
                int[] preLeft = Arrays.copyOfRange(preorder,1,i + 1);  //这里取不到i + 1，相当于一个[)
                int[] preRight = Arrays.copyOfRange(preorder,i + 1,preorder.length);

                //递归调用

                root.left = buildTree(preLeft,inleft);
                root.right = buildTree(preRight,inRight);
                break;
            }
        }



        return root;

    }


}
